<?php

/**
 * 
 */
class AgentController extends PsController
{

    public function accessRules()
    {
        return CMap::mergeArray(array(
                    array('allow',
                        'users' => array('@'),
                    ),
                        ), parent::accessRules());
    }

    public function filters()
    {
        return CMap::mergeArray(parent::filters(), array(
                    'ajaxOnly 
                + autocomplete'
				));
	}

	/**
	 * 
	 * @param type $term
	 */
	public function actionAutocomplete($term = '', $is_external = null, $property_case_id = null)
	{
		$response = array();
		$isLicenseNo = false;
		$response['input'] = $term;

		if (!is_null($property_case_id)) {
			$propertyCase = PropertyCase::model()->ofCurrentAgency()->findByPk($property_case_id);
			$internalAgencyId = $propertyCase->agency_id;
			$internalAgent = $propertyCase->user_id;
		} else {
			$internalAgencyId = Yii::app()->user->getSelectedAgency()->id;
			$internalAgent = Yii::app()->user->id;
		}


		$criteria = new CDbCriteria();
		if (strlen($term) > 0) {

			$isLicenseNo = preg_match('/^[rRpP].*[a-zA-Z]$/i', $term);

			$criteria->addCondition('t.license_no LIKE :term OR t.name LIKE :term');
			$criteria->with = array('agency');
			$criteria->together = true;
			$criteria->limit = 25;

			$criteria->params = array();
			$criteria->params[':term'] = '%' . $term . '%';

			if (strlen($is_external) > 0) {
				if ($is_external == 1) { // External cobroker
					$criteria->addCondition('t.agency_id <> :agencyId');
					$criteria->params[':agencyId'] = $internalAgencyId;
				} else { // Internal cobroker
					$criteria->addCondition('t.agency_id = :agencyId AND t.id <> :userId');
					$criteria->params[':agencyId'] = $internalAgencyId;
					$criteria->params[':userId'] = $internalAgent;
				}
			}

			$data = array();
			$users = User::model()->findAll($criteria);
			$agents = array();
			$agent = array();
			if (empty($users) && $isLicenseNo) {
				$model = PsCEADataGrabber::grabAgent($term);
				if (!empty($model)) {
					$users[] = $model;
				}
			}

			foreach ($users as $user) {
				$agent['id'] = $user->id;
				$agent['name'] = $user->name;
				$agent['user_id'] = $user->id;
				$agent['license_no'] = $user->license_no;

				if (in_array($user->agency_id, Yii::app()->user->getSelectedAgency()->getChildAgencyIds())) {
					$agent['email'] = $user->email;
					$agent['mobile'] = $user->mobile;
				}
				$agent['agency_name'] = $user->agency->name;
				$agent['agency_id'] = $user->agency_id;

				$agents[] = $agent;
			}

			$data['agents'] = $agents;
			$response['result'] = 'success';
			$response['data'] = $data;
//			$response['property_case_id'] = $property_case_id;
//			$response['internal_agency__id'] = $internalAgencyId;
//			$response['internal_agent'] = $internalAgent;
			$response['is_external'] = $is_external;
			$response['isCEALicense'] = $isLicenseNo;
		} else {
			$response['result'] = 'failure';
		}

		print json_encode($response);
	}

	public function actionLicenseCheck()
	{
		$response = array();

		$user = $_POST['user'];


		if ($user['license_no'] != '') {

			$params = array();
			$params['licenseNo'] = $user['license_no'];

			$model = User::model()->findByAttributes(array('license_no' => $user['license_no']));


			if (empty($model)) {
				$model = PsCEADataGrabber::grabAgent($user['license_no']);
			}

			$results = $model->attributes;
			$results['agency_name'] = $model->agency->name;

			$output = array('id', 'name', 'email', 'mobile', 'license_no', 'agency_name');

			foreach ($results as $key => $value) {
				if (in_array($key, $output)) {
					if ($key == 'id') {
						$response['data']['user_id'] = $value;
					} else {
						$response['data'][$key] = $value;
					}
				}
			}

			$response['result'] = 'success';
		} else {
			$response['result'] = 'failure';
			$response['errorMsg'] = 'license no is empty';
		}

		print CJSON::encode($response);
	}

	public function actionCeaupdate($id)
	{
		$response = array();
		if (isset($id)) {
			// user id
			$user = User::model()->findByPk($id);
			// fetch info from CEA
			$model = PsCEADataGrabber::grabAgent($user->license_no);

			$results = $model->attributes;
			$results['agency_name'] = $model->agency->name;

			$output = array('id', 'name', 'email', 'mobile', 'license_no', 'agency_name');

			foreach ($results as $key => $value) {
				if (in_array($key, $output)) {
					if ($key == 'id') {
						$response['data']['user_id'] = $value;
					} else {
						$response['data'][$key] = $value;
					}
				}
			}

			$response['result'] = 'success';
		} else {
			$response['result'] = 'failure';
			$response['errorMsg'] = 'no user id';
		}

		print CJSON::encode($response);
	}

}

?>
